<template>
	<el-form  :model="user"  label-width="0px" ref="loginref" class="frombox" :rules="rules">
	  <h2 class="title">系统登录</h2>
	  <el-form-item label="" prop="username">
	    <el-input  v-model="user.username" placeholder="账号" prefix-icon="el-icon-user" ></el-input>
	  </el-form-item>
	  <el-form-item label="" prop="password">
	    <el-input type="password" v-model="user.password" placeholder="密码" prefix-icon="el-icon-lock"></el-input>
	  </el-form-item>
	  <el-form-item>
	    <el-button type="primary" @click="submit('loginref')">提交</el-button>
	    <el-button @click="reset('loginref')" >重置</el-button>
	  </el-form-item>
	</el-form>
</template>

<script>
export default {
	data(){
		return{
			user:{
				username:'admin',
				password:'123456'
			},
			rules:{
				username:[
					 { required: true, message: '请输入账号', trigger: 'blur' },
					 { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
				],
				password:[
					 { required: true, message: '请输入密码', trigger: 'blur' },
					 { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' }
				]
			}
		}
	},
	methods:{
		// 重置按钮实现效果
		reset(formname){  
			this.$refs[formname].resetFields();
		},
		// 提交按钮的实现效果
		submit(formname){
			this.$refs[formname].validate(async(valide)=>{
				if(valide){ // 数据校验成功
					// 1,使用axios来请求后端的vueLogin请求
					var param = new URLSearchParams();
					param.append("username",this.user.username);
					param.append("password",this.user.password);
					var res =await this.$http.post('vueLogin',param);
					// 2, 处理结果数据
					//console.log(res)
					if(res.data.code == 200){ // 登录成功
						this.$message.success('登录成功！');
						// 将登陆成功之后的token,保存到客户端的sessionStorage中
						window.sessionStorage.setItem("token",res.data.data.token)
						// 使用编程式导航跳转到  /home
						this.$router.push('/home') 
					}else{  // 登录失败
						this.$message.error(res.data.message);
					}
				}else{  // 数据校验失败
					this.$message.error('用户名或密码不合法');
				}
			})
		}
		
	}
}
</script>

<style>
.frombox{
	border: 1px solid #DCDFE6;
	width: 300px;
	padding: 30px 50px;
	margin: 100px auto;
	border-radius: 10px;
	box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1)
}
.title{
	text-align: center;
	color: #606266;
}
</style>
